package com.scedu.convert;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scedu.domain.OrderDetail;
import com.scedu.dto.OrderDTO;
import com.scedu.enums.ResultEnums;
import com.scedu.exception.SellException;
import com.scedu.form.OrderForm;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


@Slf4j
public class OrderFomr2OrderDTOConverter {
    public  static OrderDTO convert(OrderForm orderForm){
        OrderDTO orderDTO=new OrderDTO();
        orderDTO.setOrderName(orderForm.getName());
        orderDTO.setOrderPhone(orderForm.getPhone());
        orderDTO.setOrderOpenid(orderForm.getOpenid());
        orderDTO.setOrderAddress(orderForm.getAddress());
        List<OrderDetail> orderDetailList=new ArrayList<>();
        try {
            Gson gson = new Gson();
            //json 转list
            Type orderGenericType = new TypeToken<List<OrderDetail>>() {}.getType();
            orderDetailList=gson.fromJson(orderForm.getItems(),orderGenericType);
            }
        catch (Exception e){
            log.error("对象错误，无法转换，string={}",orderForm.getItems());
            throw new SellException(ResultEnums.JSON_FORM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
       // BeanUtils.copyProperties(orderForm,orderDTO); 属性名不同，不能用copyproperties
        return orderDTO;
    }
}
